package com.qf.dblib.dao.impl;

import android.text.TextUtils;

import com.qf.dblib.dao.entity.SearchHistoryBean;
import com.qf.dblib.dao.entity.UserInfo;

import org.litepal.LitePal;

import java.util.List;

/**
 * 搜索历史记录控制类
 * 2018/4/14 15:31
 */
public class SearchHistoryDao
{
    private static volatile SearchHistoryDao instance = null;

    private UserInfo user;

    private SearchHistoryDao()
    {
        user = UserMgr.getInstance().getLoginUser();
        if (user == null) {
            user = new UserInfo();
        }
    }

    public static SearchHistoryDao getInstance()
    {
        if (instance == null)
        {
            synchronized (SearchHistoryDao.class)
            {
                if (instance == null)
                {
                    instance = new SearchHistoryDao();
                }
            }
        }
        return instance;
    }

    /**
     * 保存历史数据
     *
     * @param value    数据
     */
    public boolean saveHistory(String value)
    {
        if (TextUtils.isEmpty(value))
            throw new RuntimeException("Search Histroy value canot be null");
        //先查找，如果有相同的数据，则删除老数据
        List<SearchHistoryBean> queryBeans = LitePal.where("uid = ? and value = ?", String.valueOf(user.getUid()), value).find(SearchHistoryBean.class);
        if (queryBeans != null && queryBeans.size() > 0)
            LitePal.deleteAll(SearchHistoryBean.class, "uid = ? and value = ?", String.valueOf(user.getUid()), value);
        //插入新数据
        SearchHistoryBean bean = new SearchHistoryBean(user.getUid(), value);
        return bean.save();
    }


    /**
     * 查找最新的10条历史数据
     *
     */
    public List<SearchHistoryBean> queryHistroy()
    {
        return LitePal.where("uid = ?", String.valueOf(user.getUid())).order("id desc").limit(10).find(SearchHistoryBean.class);
    }


    /**
     * 清空所有搜索记录
     */
    public void clearAllData()
    {
        instance = null;
        LitePal.deleteAll(SearchHistoryBean.class);
    }
}
